package org.testmyapp.tasks;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.testmyapp.engine.IEngineServices;
import org.testmyapp.entities.Bill;
import org.testmyapp.persistence.BusinessObjectPersistenceProvider;

public class CorrectBill implements TaskWorker {

	public String validate(IEngineServices aes,
			Map<String, String[]> parameterMap, String processInstanceId,
			BusinessObjectPersistenceProvider bopp) {
		

		Integer billNr = Integer.parseInt(parameterMap.get("billNr")[0]);
		String optionCorrection = parameterMap.get("optionCorrection")[0];
		
		@SuppressWarnings("unchecked")
		List<Bill> bills = (List<Bill>) aes.getVariable("bills", processInstanceId); 
		Bill billToCorrect = bills.get(billNr);
		
		if(optionCorrection == null) {
			throw new RuntimeException("Error: no option for correction");
		}
		if(billToCorrect == null) {
			throw new RuntimeException("Error: no bill with nr " + billNr + " for correction");
		}		

		aes.setVariable(processInstanceId, "optionCorrection", optionCorrection);
		
		if(optionCorrection.equals("delete")) {
			aes.setVariable(processInstanceId, "objectToCorrect", billToCorrect);
			aes.setVariable(processInstanceId, "correctedObject", null);
			return "";
		}
		
		String careprovider = parameterMap.get("careprovider")[0];
		Integer billSum = Integer.parseInt(parameterMap.get("billSum")[0]);
		String beginDate = parameterMap.get("beginDate")[0];
		String endDate = parameterMap.get("endDate")[0];
		String entryDate = parameterMap.get("entryDate")[0];
		
		if(!TaskWorkersCommon.validateSum(billSum)) {
			throw new RuntimeException("Error: billSum to high for bill " + billNr + ", correction failed");
		}
		
		// Don't worry about thrown errors, they get caught one level higher
		Date begin = TaskWorkersCommon.parseDateFromString(beginDate);
		Date end = TaskWorkersCommon.parseDateFromString(endDate);
		Date entry = TaskWorkersCommon.parseDateFromString(entryDate);
		
		Bill bill = new Bill();
		bill.setBillSum(billSum);
		bill.setCareProvider(careprovider);
		bill.setEndDate(end);
		bill.setEntryDate(entry);
		bill.setStartDate(begin);
		bill.setBillNr(billNr);
		bill.setAccountingMedical(billToCorrect.getAccountingMedical());
		
		aes.setVariable(processInstanceId, "correctedObject", bill);
		aes.setVariable(processInstanceId, "objectToCorrect", billToCorrect);
		
		return "";
	}

}
